import Taro from "@tarojs/taro";
import React, { useEffect, useImperativeHandle, useState } from "react";
import { View } from "@tarojs/components";
import { Empty, InfiniteLoading } from "@nutui/nutui-react-taro";


// import { queryElementInfo } from "../../utils";
import "./pageList.scss";

// interface IProps {
//   renderItem: (data) => React.ReactNode;
//   request: (params) => Promise<any>;
//   params: Record<string, any>;
//   dataKey?: string;
//   renderHeader?: () => React.ReactNode;
//   renderFoot?: () => React.ReactNode;
//   requestCallback?: (data: any) => void;
//   extraHeight?: number;
// }

function PageList(props, ref) {
  const [pageNum, setPageNum] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [listHeight, setListHeight] = useState(0);
  const [isEmpty, setIsEmpty] = useState(false);
  const [listData, setListData] = useState([]);

  useImperativeHandle(ref, () => ({
    refresh: refresh,
  }));

  useEffect(() => {
    init();
  }, [props.params, props?.extraHeight]);

  async function init() {
    const listHeaderInfo = await queryElementInfo("#list-header");
    const listFootInfo = await queryElementInfo("#list-foot");
    const systemInfo = Taro.getSystemInfoSync();
    const windowHeight = systemInfo.windowHeight;
    const targetListHeight =
      windowHeight -
      (listHeaderInfo?.height ?? 0) -
      (listFootInfo?.height ?? 0) -
      (props?.extraHeight || 0);
    setListHeight(targetListHeight);
    await refresh();
  }


  // 获取元素数据
function queryElementInfo(ele) {
  return new Promise((resolve) => {
    const query = Taro.createSelectorQuery();
    query
      .select(ele)
      .boundingClientRect((rec) => {
        resolve(rec);
      })
      .exec();
  });
}


  const loadMore = async()=> {
    // console.log("done",done);
    const pageNo = pageNum + 1;
    console.log("pageNo",pageNo);
    setPageNum(pageNo);
    await getList(pageNo);
    // done();
  }

  async function refresh(done) {
    Taro.showLoading({ title: "刷新中..." });
    setPageNum(1);
    await getList(1);
    Taro.hideLoading();
    done && done();
  }

  async function getList(pageNo) {
    const params = {
      pageNum: pageNo,
      ...props.params,
    };

    const { data, success, msg } = await props?.request(params);

    if (!success) {
      Taro.showToast({
        title: msg || "请求失败!",
        icon: "none",
        duration: 3000
      });
    }

    props?.requestCallback && props?.requestCallback({ data, success, msg });

    let list = [];
    list =
      pageNo > 1
        ? [...listData, ...data?.[props?.dataKey || "list"]]
        : data?.[props?.dataKey || "list"] || [];

    setHasMore(list?.length < data?.total);
    setIsEmpty(data?.total === 0);
    setListData(list);
  }

  return (
    <View className="component-page-list">
      <View id="list-header">
        {props?.renderHeader && props?.renderHeader()}
      </View>
      <View
        id="pageList"
        style={{
          height: listHeight,
          paddingTop: "20rpx",
          boxSizing: "border-box",
        }}
      >
        <InfiniteLoading
          pullingText={<span style={{ fontSize: "26rpx" }}>松开刷新</span>}
          loadingText="加载中···"
          loadMoreText="没有啦～"
          pullRefresh
          target="pageList"
          hasMore={hasMore}
          onLoadMore={loadMore}
          onRefresh={refresh}
        >
          {isEmpty ? (
            <Empty style={{ height: listHeight - 35 }} description="无数据" />
          ) : (
            listData?.map((item) => props.renderItem(item))
          )}
        </InfiniteLoading>
      </View>
      <View id="list-foot" style={{ opacity: !!listHeight ? 1 : 0 }}>
        {props.renderFoot && props.renderFoot()}
      </View>
    </View>
  );
}

export default React.forwardRef(PageList);
